<template>
<el-upload
  v-model:file-list="fileList"
  action="http://127.0.0.1:8081/upload"
  list-type="picture-card"
  :on-preview="handlePictureCardPreview"
  :on-remove="deleteProductResource1"
  :on-success="handleUploadSuccess"
>
  <el-icon><Plus /></el-icon>
</el-upload>

<el-dialog v-model="dialogVisible">
  <img w-full :src="dialogImageUrl" alt="Preview Image" />
</el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import type { UploadProps, UploadUserFile } from 'element-plus';
import type { ProductResource } from "@/common/types/commonTypes";
import {ElMessage, ElMessageBox} from "element-plus";
import {createProductResource, deleteProductResource, getProductResourcesByProductId} from "@/common/net/api";

const props = defineProps({
  currentProductId:{
    type:Number,
    required:true
  }
});
const fileList = ref([
]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  // 向父组件发送事件，通知文件移除操作完成
  emit('update:fileList', uploadFiles);
};

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const emit = defineEmits(['update:fileList']);
async function fetchProductResources(productId: number) {
  try {
    const response = await getProductResourcesByProductId(productId);
    console.log(response)
    fileList.value = response.data.data
  } catch (error) {
    console.error('获取商品资源失败:', error);
    ElMessage.error('获取商品资源失败');
  }
}

const deleteProductResource1: UploadProps['onRemove'] = async (uploadFile, uploadFiles) => {
  ElMessageBox.confirm('确定要删除该资源吗？', '删除资源', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    console.log(uploadFile)
    await deleteProductResource(uploadFile.id).then(res=>{
      if (res.data.state){
        console.log(res)
        ElMessage.success('删除成功');
        fetchProductResources(props.currentProductId);
      }else{
        ElMessage.error('删除失败');
      }
    })
  })}
const addResource = async (response:any,file: File) => {
  const fileType = getFileType(file);
  let r1: ProductResource = {
    productId: props.currentProductId,
    url: response.data,
    type: fileType // 添加文件类型字段
  };
  try {
    const response = await createProductResource(r1).then(res=>{
      ElMessage.success('添加成功');
      fetchProductResources(props.currentProductId);
    });
  } catch (error) {
    ElMessage.error('添加失败');
  }
};
const handleUploadSuccess: UploadProps['onSuccess'] = (response, file) => {
  addResource(response, file.raw!); // 调用 addResource 方法
};
const getFileType = (file: File): number => {
  const mimeType = file.type;
  if (mimeType.startsWith('image/')) {
    return 1;
  } else if (mimeType.startsWith('video/')) {
    return 2;
  } else {
    return 3;
  }
};
const refreshFileList = () => {
  fetchProductResources(props.currentProductId);
};

fetchProductResources(props.currentProductId);
defineExpose({
  refreshFileList
});
</script>
